package org.grayrabbit.cms.util;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.grayrabbit.cms.entity.Admin;
import org.grayrabbit.cms.entity.AdminOperRela;
import org.grayrabbit.cms.entity.OperCode;
import org.grayrabbit.cms.entity.Role;
import org.grayrabbit.cms.entity.RoleOperRela;
import org.grayrabbit.cms.vo.system.AuthBean;


public class OperCodeJSONUtil { 
	
	/**
	 * @param JSONString
	 * @return
	 */
	private static List<AuthBean>  fromJSONToObject(String JSONString){
		List<AuthBean> list = new ArrayList<AuthBean>();
		if(StringUtils.isBlank(JSONString)) 
			return list;
		 
		JSONArray array =JSONArray.fromObject(JSONString); 
		@SuppressWarnings("rawtypes")
		ListIterator it = array.listIterator();
    	while(it.hasNext()){
    		AuthBean bean= (AuthBean)JSONObject.toBean(JSONObject.fromObject(it.next()),AuthBean.class);
    		list.add(bean);	 
	    }
		return list;
	}
	
	public static List<String> splitTargetIds(String  targetIds) {
		 List<String>  targetId = new ArrayList<String>(); 
		 if(StringUtils.isBlank(targetIds)) return targetId;
		 String[] ids = targetIds.split("-");
		 if(ids.length >AuthBean.MAX_NUM){
			 StringBuffer sb = new StringBuffer();
			 int i=0;
			 int j=0;
			 for(String id :ids){
				 sb.append(id);
				 i++; 
				 j++;
				 if(i==AuthBean.MAX_NUM){
					 targetId.add(sb.toString());
					 i=0;
				     sb=new StringBuffer();				 
				 }else if(i!=AuthBean.MAX_NUM && j!=ids.length ){
					 sb.append("-");
				 }else if(j==ids.length){
					 targetId.add(sb.toString());
					 sb=null;
				 }
			 } 
		 }else{
			 targetId.add(targetIds);
		 }
		 return targetId;
  
	}

	public static List<RoleOperRela>  getRoleAuth(String JSONString,String ObjectId,String ObjectType){
		List<RoleOperRela> list = new  ArrayList<RoleOperRela>();
		List<AuthBean>  beans =fromJSONToObject(JSONString);
		RoleOperRela rale = null;
		Role role = null;
		OperCode code = null;
		for(AuthBean b : beans){ 
			role = new Role();
			code = new OperCode();
			rale = new RoleOperRela();
			
			role.setRoleId(ObjectId);
			code.setOperId(b.getOperId());
			
			rale.setRole(role);
			rale.setOperCode(code);
			rale.setOperTargetType(b.getTargetType());	
			if(StringUtils.isNotBlank(b.getTargetIds()) && b.getTargetIds().length()>AuthBean.TARGET_IDS_MAX_LENGTH){
				List<String>  ids =splitTargetIds(b.getTargetIds());				
				if(ids.size()>0) rale.setOperTargetId(ids.get(0));
				if(ids.size()>1) rale.setOperTargetId2(ids.get(1));
				if(ids.size()>2) rale.setOperTargetId3(ids.get(2));
				if(ids.size()>3) rale.setOperTargetId4(ids.get(3));
				if(ids.size()>4) rale.setOperTargetId5(ids.get(4));
    		}else{    			
    			rale.setOperTargetId(b.getTargetIds());
    		}
			
			list.add(rale); 
		}
		return list;
	}
	
	public static List<AdminOperRela>  getAdminAuth(String JSONString,String ObjectId,String ObjectType){
		List<AdminOperRela> list = new  ArrayList<AdminOperRela>();
		List<AuthBean>  beans =fromJSONToObject(JSONString);
		AdminOperRela rale = null;
		Admin admin = null;
		OperCode code = null;
		for(AuthBean b : beans){ 
			admin = new Admin();
			code = new OperCode();
			rale = new AdminOperRela();
			
			admin.setAdminId(ObjectId);
			code.setOperId(b.getOperId());			
			rale.setAdmin(admin);
			rale.setOperCode(code);
			rale.setOperTargetType(b.getTargetType());			
			if(StringUtils.isNotBlank(b.getTargetIds()) && b.getTargetIds().length()>AuthBean.TARGET_IDS_MAX_LENGTH){
				List<String>  ids =splitTargetIds(b.getTargetIds());				
				if(ids.size()>0) rale.setOperTargetId(ids.get(0));
				if(ids.size()>1) rale.setOperTargetId2(ids.get(1));
				if(ids.size()>2) rale.setOperTargetId3(ids.get(2));
				if(ids.size()>3) rale.setOperTargetId4(ids.get(3));
				if(ids.size()>4) rale.setOperTargetId5(ids.get(4));
    		}else{    			
    			rale.setOperTargetId(b.getTargetIds());
    		}
			list.add(rale); 
		}
		return list;
	}
	
	private static List<AuthBean>  getAdminAuthBean(List<AdminOperRela> list){
		if(list == null || list.isEmpty()) return null;
		List<AuthBean> beans = new ArrayList<AuthBean>();
		AuthBean authBean = null;
		for(AdminOperRela rela:list){
			authBean = new AuthBean();
			authBean.setOperId(rela.getOperCode().getOperId());
			String tids = loadTargetIds(rela.getOperTargetId(), 
					rela.getOperTargetId2(),rela.getOperTargetId3(), 
					rela.getOperTargetId4(), rela.getOperTargetId5());
			authBean.setTargetIds(tids);
			authBean.setTargetType(rela.getOperTargetType());
			beans.add(authBean);
		} 
		return beans;
	}
	
	
	private static List<AuthBean> getRoleAuthBean(List<RoleOperRela> list){
		if(list == null || list.isEmpty()) return null;
		List<AuthBean> beans = new ArrayList<AuthBean>();
		AuthBean authBean = null;
		for(RoleOperRela rela:list){
			authBean = new AuthBean();
			authBean.setOperId(rela.getOperCode().getOperId());
			String tids = loadTargetIds(rela.getOperTargetId(), 
				rela.getOperTargetId2(),rela.getOperTargetId3(), 
				rela.getOperTargetId4(), rela.getOperTargetId5());
			authBean.setTargetIds(tids);
			authBean.setTargetType(rela.getOperTargetType());
			beans.add(authBean);
		} 
		return beans;
	}
	
	public static String  fromRoleOperRelaToJSON(List<RoleOperRela> list){
		List<AuthBean> beans = getRoleAuthBean(list);
		return toJSONString(beans);
	}
	
	public static String  fromAdminOperRelaToJSON(List<AdminOperRela> list){
		List<AuthBean> beans = getAdminAuthBean(list);
		return toJSONString(beans);
	}
	
	private static String toJSONString(List<AuthBean> list){
		if(list == null || list.isEmpty()) return null;
		StringBuffer sb = new StringBuffer();
		sb.append("[");
		int i=list.size();
		for(AuthBean b: list){
			i--;
			sb.append("{operId:'"+b.getOperId()+"',targetIds:'"+b.getTargetIds()+"',targetType:'"+b.getTargetType()+"'}");
			if(i!=0){
				sb.append(",");
			} 
		}
		sb.append("]");		
		return sb.toString();
	}
	
	private static String  loadTargetIds(String t,String t2,String t3,String t4,String t5){
		Set<Object> set = new HashSet<Object>();	
		loadTargetIdSet(set, t);
		loadTargetIdSet(set, t2);
		loadTargetIdSet(set, t3);
		loadTargetIdSet(set, t4);
		loadTargetIdSet(set, t5); 
		return join(set, "-");
	} 
	
	private  static void  loadTargetIdSet(Set<Object> set ,String targetId ){
		if(StringUtils.isBlank(targetId))  return ;
		String[] ids = targetId.split("-");
		for(String s : ids){			
			set.add(s);
		}
	}
	
	/**
	 * @param set  String set
	 * @param split
	 * @return
	 */
	public  static String join(Set<Object> set,String split){
		if(set==null || set.isEmpty())  return null;
		int i = set.size();
		StringBuffer sb = new StringBuffer();
		for(Object s :set){
			i--;
			sb.append((String)s);
			if(i != 0) sb.append(split);
		}
		return sb.toString();
	}
	
	/**
	 * * 删除栏目 、站点、专题 时删除权限service调用
	 * @param ids
	 * @param id
	 * @return
	 */
	public static String delteTargetIds(String ids,String id){
		if(StringUtils.isBlank(ids))  return null;
		ids = ids.replace(id, "");
		ids = ids.replaceAll("-{2,}", "-");
		if(ids.length()<32){
			return null;			
		}else{
			if(ids.startsWith("-")){
				ids = ids.substring(1, ids.length());
			}
			if(ids.endsWith("-")){
				ids = ids.substring(0, ids.length()-1);
			}
			return ids;
		}
	}
	
	/**
	 *  增加栏目 、站点、专题 时 赋予相应的管理权限  service调用
	 * @return
	 */
	public static void addObjectAuth(String t,String t2,String t3,String t4,String t5,Set<Object> set ){
		loadTargetIdSet(set, t);
		loadTargetIdSet(set, t2);
		loadTargetIdSet(set, t3);
		loadTargetIdSet(set, t4);
		loadTargetIdSet(set, t5);		
	}	
	public static void main(String[] args) { 
		 String y =loadTargetIds("wqe-qwe-qwe-213", "wqe-qwe-qwe-213", 
				 "w1qe-qwe-qw2e-213","wqe-3qwe-qwe-213", "wqe4-qwe-qwe4-213");
		
		
		System.out.println(y); 
	}
}
